﻿using NewLife.Log;
using NewLife.MQTT;
using NewLife.Security;

namespace Test
{
    internal class Program
    {
        private static void Main(String[] args)
        {
            XTrace.UseConsole();
            XTrace.Log.Level = LogLevel.Debug;

            try
            {
                Test2();
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

            Console.WriteLine("OK");
            Console.Read();
        }

        private static MqttClient _mc;
        /// <summary>
        /// 测试完整发布订阅
        /// </summary>
        private static async void Test1()
        {
            _mc = new MqttClient
            {
                Log = XTrace.Log,
                Server = "tcp://127.0.0.1:51883",
                ClientId = $"{Environment.MachineName}_MQTT",
                //UserName = "admin",
                //Password = "admin",
            };

            await _mc.ConnectAsync();
            //订阅“/test”主题
            var rt = await _mc.SubscribeAsync("/test", (e) =>
            {
                XTrace.WriteLine("MQTT_消费消息:" + "/test/# =>" + e.Topic + ":" + e.Payload.ToStr());
            });

            var seq = 1;
            while (true)
            {
                //每2秒向“/test”主题发布一条消息
                try
                {
                    var msg = $"hello-{seq}";
                    await _mc.PublishAsync("/test", msg);
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                }
                seq++;
                await Task.Delay(2000);
            }
        }

        /// <summary>
        /// 测试完整发布订阅
        /// </summary>
        private static async void Test2()
        {
            if (_mc == null || !_mc.IsConnected)
            {
                _mc = new MqttClient
                {
                    Log = XTrace.Log,
                    Server = "tcp://127.0.0.1:51883",
                    ClientId = $"{Environment.MachineName}_PUB_{Environment.ProcessId}",
                    //UserName = "admin",
                    //Password = "admin",
                };

                await _mc.ConnectAsync();
            }

            if (_mc?.IsConnected ?? false)
            {
                var seq = 1;
                while (true)
                {
                    //每2秒向“/test”主题发布一条消息
                    try
                    {
                        var msg = $"hello-{seq}";
                        await _mc.PublishAsync("/test", msg);
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex);
                    }
                    seq++;
                    await Task.Delay(1000 * 60 * 2);
                }
            }
        }
    }
}